import {XgPlayer} from "../index";

export class XgControlSlider {
  root!: HTMLInputElement;
  constructor(private player: XgPlayer) {
    this.init();
  }
  private init() {
    this.root = document.createElement('input');
    this.root.className = 'slider';
    this.root.setAttribute('type', 'range');
    this.root.setAttribute('min', '0');
    this.root.setAttribute('max', '100');
    this.setValue(0);
    this.player.emitter.on('timeupdate', this.handleTimeUpdate.bind(this));
    this.root.addEventListener('change', this.handleSeeking.bind(this));

  }
  private handleTimeUpdate(time: number) {
    // console.log('handleTimeUpdate>>', time);
    const { duration } = this.player.videoInstance.videoEl;
    if (duration) {
      const value = time * 100 / duration;
      this.setValue(value);
    }
  }
  private handleSeeking() {
    const currentTime = this.player.videoInstance.videoEl.duration * +this.root.value / 100;
    console.log('handleSeeking currentTime', currentTime);
    this.player.videoInstance.seeking(currentTime);
  }
  private setValue(value: number) {
    // console.log('setValue', value);
    this.root.setAttribute('value', Math.round(value).toString());
  }
}
